package com.gym.myshop.dao.impl;

import com.gym.myshop.dao.OrderDao;
import com.gym.myshop.entity.Address;
import com.gym.myshop.entity.Orders;
import com.gym.myshop.util.DBUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author ming
 * 2021/11/8
 * description:订单
 */
public class OrderDaoImpl implements OrderDao {
    private QueryRunner qr = new QueryRunner();

    /**
     *@author:ming
     *@Date: 2021/11/8
     *@description:生成订单
     *iid订单项的唯一标识 oid订单编号是字符串类型但是也是唯一标识
     * pid商品的唯一主键 Icount订单项的小计  Inum订单项的商品数量
     */
    @Override
    public int addOrder(Orders o) throws SQLException {
        return qr.update(DBUtil.getConnection(), "insert into orders values (?,?,?,?,?,?)",
                o.getOid(), o.getUid(), o.getAid(), o.getOcount(), o.getOtime(), o.getOstate());
    }

    /**
     *@author:ming
     *@Date: 2021/11/8
     *@description:获取订单列表信息
     * aid地址实体的唯一主键列  uid用户实体的主键属性
     */
    @Override
    public List<Orders> getOrderList(int uid) throws SQLException, InvocationTargetException, IllegalAccessException {
        String sql = "select * from orders o inner join address a on o.aid=a.aid where o.uid=?";
        List<Map<String, Object>> query = qr.query(DBUtil.getConnection(), sql, new MapListHandler(), uid);
        if (query != null) {
            //创建itemLIst用于转存地址的数据
            List<Orders> orders = new ArrayList<>();
            for (Map<String, Object> stringObjectMap : query) {
                Orders o = new Orders();
                Address a = new Address();
                BeanUtils.populate(o, stringObjectMap);
                BeanUtils.populate(a, stringObjectMap);
                //下单地址信息
                o.setAddress(a);
                orders.add(o);
            }
            return orders;
        }
        return null;
    }
}
